import React, { useEffect, useRef, useState, useContext, useCallback } from 'react';
import { Graph, Node, Shape } from '@antv/x6';
import { Button, Space, Popover, Select, Input, Flex, Modal, message } from 'antd';
import {
  X6_PORT_OUT_NAME,
  X6_PORT_OUT_NAME1,
  X6_NODE_NAME,
  PORT_HOVER,
  PORT_SELECTED,
  PORT,
  NODE,
  NODE_HOVER,
  NODE_SELECTED,
  EDGE,
  EDGE_SELECTED,
  EDGE_HOVER,
} from './dag-config'
import useModal from '../hooks/useModal';
import _ from 'lodash';
import { uniqueId, random, times } from 'lodash';
import { Edge } from '@antv/x6';
import { dataTypeEnum, DimensionMeasurementEnum, } from '@/components/workbenches/hooks/type';
import dynamic from 'next/dynamic';
import { ChatContext } from '@/app/chat-context';
import { WorkbenchesContext, } from '@/components/workbenches/workbenches-context';
import { updateStatus } from '@/client/api/workbenches';
import { DagreLayout } from '@antv/layout';
import { cloneDeep } from 'lodash';
import { useTranslation } from 'react-i18next';
const CustomNode = dynamic(() => import('../CustomNode'), {
  ssr: false,
});

const NODE_HEIGHT = 240;
const NODE_HIDE_HEIGHT = 60;
const NODE_WIDTH = 520;
let hoverCell: any = null;
const generateRandomId = (length = 6) => {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  return times(length, () => chars.charAt(random(0, chars.length - 1))).join('') + uniqueId();
};
interface paramsType {
  graph: any,
  handleCreate: (edge: Edge, modalType: 'add' | 'edit') => void,
  setCopilotVisible: (boolean: boolean) => void,
  canvasResizeChange: () => void,
}

export default function useCanves({ graph, handleCreate, setCopilotVisible, canvasResizeChange, }: paramsType) {
  const { t, i18n } = useTranslation();
  const container = useRef<HTMLDivElement>(null);
  const nodeCount = useRef(1);
  const [nodesData, setNodesData] = useState<Record<string, { name: string; type: string }[]>>({});
  const { mode } = useContext(ChatContext);
  const {
    currentItem,
    activeKey,
  } = useContext(WorkbenchesContext);

  const [saveState, setSaveState] = useState({} as any);
  const setSaveStateChange = (data: any) => {
    const { id, } = data || {};
    if (!saveState?.[id]) {
      setSaveState((v: any) => ({ ...v, [id]: { ...saveState[id], ...data } }));
    }
  }
  const customizeComponentRenderChange = ({ id, businessData }:
    { id: string, businessData: { dataList: any[], tableType: '' | '0' | '1', describe: string }, }) => {
    return <CustomNode
      graph={graph}
      id={id}
      data={{ ...businessData }}
      currentItem={currentItem}
      setSaveStateChange={setSaveStateChange}
      updateNodeData={updateNodeData}
      removeNode={removeNode}
      updateNodeStyle={updateNodeStyle}
      getNodeData={getNodeData}
      setCopilotVisible={setCopilotVisible}
    />
  }
  const removeNode = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '删除节点将同时删除相关连线，是否继续？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        if (graph.current) {
          const node = graph.current.getCellById(id);
          if (node) {
            // 获取所有相关的边
            const connectedEdges = graph.current.getConnectedEdges(node);

            // 先删除相关的边
            connectedEdges.forEach(edge => {
              edge.remove();
            });

            // 删除节点
            node.remove();

            // 更新状态
            setNodesData((prev) => {
              const copy = { ...prev };
              delete copy[id];
              return copy;
            });

            // 更新节点计数
            nodeCount.current = Math.max(0, nodeCount.current - 1);

            applyDagreLayout();
          }
        }
      }
    });
  }
  const updateNodeData = (id: string, newData: Array<{ name: string; type: string }>) => {
    setNodesData((prev) => {
      const copy = { ...prev };
      if (copy[id]) {
        copy[id] = newData;
        const node = graph.current?.getCellById(id) as Node;
        if (node) {
          const oldData = node.getData() || {};

          const data = {
            ...oldData,
            dataList: newData,
          };
          node.setData(cloneDeep(data),
            {
              overwrite: true,
              deep: true
            }
          );
        }
      }
      return copy;
    });
  };
  const updateNodeStyle = (nodeInfo: { id: string, show: boolean }) => {
    if (!nodeInfo.id) return;
    const targetNode = graph.current.getCellById(nodeInfo.id) as Node;
    if (targetNode) {
      targetNode.resize(NODE_WIDTH, nodeInfo.show ? NODE_HEIGHT : NODE_HIDE_HEIGHT);
      // targetNode.attr({
      //   body: {
      //     fill: '#ff9900',
      //     stroke: '#e68a00',
      //     strokeWidth: 3
      //   },
      //   text: {
      //     fill: '#fff',
      //     fontSize: 16
      //   }
      // });
    }
  }
  useEffect(() => {
    if (typeof window !== 'undefined' && container.current) {
      graph.current = new Graph({
        container: container.current,
        // width: 1000,
        // height: 600,
        grid: { size: 10, visible: true },
        // background: { color: '#F8F9FA' },
        mousewheel: {
          enabled: true, zoomAtMousePosition: true,
          modifiers: ['ctrl', 'meta'],
          minScale: 0.5,
          maxScale: 2,
        },
        connecting: {
          snap: true,
          allowBlank: false,
          allowLoop: false,
          highlight: true,
          connector: 'smooth',
          connectionPoint: 'boundary',
          allowMulti: false,
          allowEdge: false,
          allowNode: false,
          allowPort: true,
          createEdge() {
            // EDGE.label = link.value
            return new Shape.Edge(EDGE)
          },
          validateConnection(data) {
            return true;
            // const { sourceCell, targetCell, sourceMagnet, targetMagnet } = data;
            // // nodeInfoPopover.value = false;
            // // // 获取源连接桩和目标连接桩的类型
            // // const sourcePortType = sourceMagnet.getAttribute('port-group');
            // // const targetPortType = targetMagnet.getAttribute('port-group');

            // // // 如果源连接桩和目标连接桩都是输出连接桩，则返回 false
            // // if ((sourcePortType === 'in' && targetPortType === 'in') || (sourcePortType === 'out' && targetPortType === 'out')) {
            // //   // message.warning('不能连接相同类型的连接桩！')
            // //   return false;
            // // }

            // if (
            //   sourceCell &&
            //   targetCell &&
            //   sourceCell.isNode() &&
            //   targetCell.isNode()
            // ) {
            //   const sourceData = sourceCell.getData()
            //   const targetData = targetCell.getData();

            //   // if (!sourceData.isMainTable && !targetData.isMainTable) {
            //   //   return false;
            //   // }
            //   if (!sourceData) return true
            //   const edges = graph?.current.getConnectedEdges(sourceCell)
            //   if (!edges || edges.length < 2) return true
            //   let len = 0
            //   return !edges.some((edge: any) => {
            //     if (edge.getSourceCellId() === sourceCell.id) {
            //       len++
            //     }
            //     return len > 2
            //   })
            // }
            // return true // 允许连接
          }


        },
        snapline: true,
        scroller: {
          enabled: true,
          // pageVisible: true,
          pageBreak: true,
          pannable: true,
        },
        interacting: {
          edgeLabelMovable: true,
        },
      });
      canvasResizeChange();
    }
    monitorEvents();
    return () => {
      graph.current?.dispose();
    };


  }, []);


  const handleAddNode = (config: any = {}) => {
    if (graph.current) {
      const { id: _id, dataList: _dataList, tableType, describe, x: _x, y: _y, } = config;
      const id = `${_id || generateRandomId()}`;
      const dataList: any[] = _dataList || [
        // { name: '姓名', field: 'namfdsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssse', metrics: DimensionMeasurementEnum.Dimension, dataType: dataTypeEnum.STRING },
        // { name: '描述', field: 'desc', metrics: DimensionMeasurementEnum.Dimension, dataType: dataTypeEnum.STRING },
        // { name: '时间', field: 'time', metrics: DimensionMeasurementEnum.Dimension, dataType: dataTypeEnum.TIME },
        // { name: '年龄', field: 'age', metrics: DimensionMeasurementEnum.Measurement, dataType: dataTypeEnum.NUMBER }
      ];
      setNodesData((prev) => ({ ...prev, [id]: dataList }));

      const nodeNum = graph.current.getNodes().length;
      let x = 100;
      let y = 60 + (nodeCount.current - 1) * (NODE_HEIGHT + 60);
      if (_x != null && _x !== '') {
        x = _x;
      }
      if (_y != null && _y !== '') {
        y = _y;
      }
      const newNode = graph.current.addNode({
        id,
        shape: 'react-shape',
        x,
        y,
        width: NODE_WIDTH,
        height: NODE_HEIGHT,
        data: {
          id,
          dataList,
          tableType,
          describe,
          // isMainTable: nodeNum % 2 === 0,
        },
        component: customizeComponentRenderChange({
          id,
          businessData: {
            dataList,
            tableType: tableType || '',
            describe: describe || ''
          },
        }),
        ports: PORT,
      });
      setNodeStyle(newNode);

      nodeCount.current++;
      applyDagreLayout();
    }
  };

  const handleSave = () => {
    if (graph.current) {

      const nodes = graph.current.getNodes();
      if (!nodes?.length) {
        message.error('请添加节点');
        return;
      }
      const tjldResult = [];
      const jhfsResult = [];
      for (const key in checkedState) {
        if (Object.prototype.hasOwnProperty.call(checkedState, key) && key.startsWith('tjld') && checkedState[key] === true) {
          tjldResult.push(key);
        }
        if (Object.prototype.hasOwnProperty.call(checkedState, key) && key.startsWith('jhfs') && checkedState[key] === true) {
          jhfsResult.push(key);
        }
      }
      if (!tjldResult?.length) {
        message.error('未配置统计粒度');
        return;
      }
      if (!jhfsResult?.length) {
        message.error('未配置聚合方式');
        return;
      }
      // console.log(tjldResult, jhfsResult, 'jhfsResultjhfsResult');

      let dataList = [];
      for (const i of nodeData as any[]) {
        if (i.dataList?.length) {
          dataList.push(...i.dataList);
        }
      }
      const AnnotationIsEmpty = dataList.find(i => !i.name == null || i.name == '');
      if (AnnotationIsEmpty) {
        message.error('存在未填的注释');
        return;
      }
      const dimension = dataList.find(i => i.metrics == DimensionMeasurementEnum.Dimension);
      if (!dimension) {
        message.error('未配置维度');
        return;
      }
      const measurement = dataList.find(i => i.metrics == DimensionMeasurementEnum.Measurement);
      if (!measurement) {
        message.error('未配置度量');
        return;
      }
      const timeDimension = dataList.filter(i => 'isTimeDimension' in i && i.isTimeDimension);
      if (!timeDimension?.length) {
        message.error('未配置时间维度');
        return;
      }
      if (timeDimension?.length != 1) {
        message.error('只能选择一个时间维度');
        return;
      }
      const flag = checkNodeConnections();
      if (!flag) {
        message.error('存在未连接的节点');
        return;
      }
      // 连接线配置
      const edges = graph.current.getEdges();
      const checkEdge = edges.find((i: any) => {
        const data = i.getData();
        if (!data.join) {
          message.error(t('w_checkJoin'));
          return;
        }
        const length = !data?.fields?.length;
        if (length) {
          message.error(t('w_join'));
        }
        const item = data.fields.filter(Boolean).find((item: any) => !item?.lField || !item?.rField)
        if (item) {
          message.error(t('w_checkFieldisempty'));
        }
        return length || item;
      })
      if (checkEdge) {
        return;
      }

      let isLackInfo = true; // 是否缺少信息
      // 新增模型后删除表、查询、字段等信息提示信息（编辑时）
      for (const key in saveState) {
        const item = saveState[key];
        const { id, describe, field } = item || {}
        if (id && (!describe || !field)) {
          const node = graph.current?.getCellById(id) as Node;
          if (node) {
            let htmlDiv = null
            const view = graph.current?.findViewByCell(node);
            if (view && view.container) {
              htmlDiv = view.container.querySelector('div');
            }

            isLackInfo = false;
            if (htmlDiv) {
              htmlDiv.style.borderRadius = '4px';
              htmlDiv.style.border = '1px solid rgb(250,219,20)';
            }
          }
        }

      }
      if (!isLackInfo) {
        message.error('请检查节点信息!');
        return;
      }

      const data = graph.current.toJSON();
      console.log('保存的数据:', saveState, data, '---', _.cloneDeep(data));
      // console.log('nodeData', dataList, nodeData)
      return data;
    }
  };
  const toJSONChange = (currentItem: any) => {

    const data = graph.current.toJSON();

    data.cells.map(i => {
      if (i.shape == 'react-shape') {
        const node = graph.current?.getCellById(i.id) as Node;
        if (node) {
          node.setData({ tabItem: currentItem });
        }
      }
    })
    console.log('保存的数据:', graph.current.toJSON(), currentItem, data, '---', _.cloneDeep(data));
  }

  //事件
  function monitorEvents() {
    const highlightedEdges = new Set();
    // 鼠标移入
    graph.current.on("node:mouseenter", ({ e, cell, shape, node }) => {
      hoverCell = cell
      updateCellStyle(cell)
    });
    // 鼠标移出
    graph.current.on('node:mouseleave', ({ cell, shape, node }) => {
      hoverCell = null
      updateCellStyle(cell)
    });

    graph.current.on('edge:mouseenter', ({ edge }) => {
      // hoverCell = edge
      updateCellStyle(edge)
    })

    graph.current.on('cell:mouseenter', ({ cell, shape, node, view, e }) => {
      if (node) {
        // 当前节点的连线高亮
        const connectedEdges = graph.current.getConnectedEdges(cell);
        connectedEdges.forEach((edge) => {
          // 高亮显示边
          edge.attr({
            line: { stroke: '#B620E0', strokeWidth: 1 },
          });
          highlightedEdges.add(edge);
        });
      }
    });
    // 鼠标移出
    graph.current.on('cell:mouseleave', ({ cell, shape, node }) => {
      // 取消高亮显示的边
      highlightedEdges.forEach((edge) => {
        edge.attr({ line: { stroke: "rgb(155,169,195)", strokeWidth: 0.8 } });
      });
      highlightedEdges.clear();
    });
    graph.current.on('edge:mouseleave', ({ edge }) => {
      // hoverCell = null
      updateCellStyle(edge)
    })

    graph.current.on('edge:selected', ({ edge }) => {
      // hoverCell = edge
      updateCellStyle(edge)
    })

    graph.current.on('edge:unselected', ({ edge }) => {
      // hoverCell = edge
      updateCellStyle(edge)
    })


    //连线结束后
    graph.current.on('edge:connected', ({ isNew, edge }) => {
      if (isNew) {
        const source = edge.getSourceCell()
        const target = edge.getTargetCell()
        handleCreate(edge, 'add')
        // console.log('isNew, edge', isNew, edge, source, target, source.getData(), target.getData())
      }

    })


    //  选中节点
    graph.current.on("cell:selected", ({ cell }) => {
      hoverCell = cell
      updateCellStyle(cell)
    });

    // 取消选中节点
    graph.current.on("cell:unselected", ({ cell }) => {

      updateCellStyle(cell)
    });

    graph.current.on('edge:contextmenu', ({ cell, node, e, x, y, edge }) => {
      e.stopPropagation();
      e.preventDefault();
      const view = graph.current.findViewByCell(edge);
      if (view) {
        setEdgeContextMenu({ cell, edge, x: e.clientX, y: e.clientY, view });
      }
    });
  }

  // 鼠标事件更新样式
  function updateCellStyle(cell) {
    if (cell.isEdge()) {
      setEdgeStyle(cell)
    } else if (cell.isNode()) {
      setNodeStyle(cell)
    }
  }

  //连线样式
  function setEdgeStyle(edge) {
    const isHover = edge === hoverCell
    const isSelected = graph.current.isSelected(edge)
    let edgeProps = null
    if (isHover) {
      edgeProps = _.merge(_.cloneDeep(EDGE), EDGE_HOVER)
    } else if (isSelected) {
      edgeProps = _.merge(_.cloneDeep(EDGE), EDGE_SELECTED)
    } else {
      edgeProps = _.cloneDeep(EDGE)
    }
    edge.setAttrs(edgeProps.attrs)
    edge.setLabels([
      {
        ..._.merge(
          {
            attrs: _.cloneDeep(edgeProps.defaultLabel.attrs)
          }
        )
      }
    ])
    const { join } = edge.getData() || {}

    // 边线保留 标签
    edge.appendLabel({
      attrs: {
        label: { text: join || '', fill: "#fff", },
        body: {
          ref: "label",
          fill: "#B620E0",
          stroke: "#444",
          strokeWidth: 1,
          cursor: 'pointer'
        },
      }
    })

  }


  //节点样式
  function setNodeStyle(node) {
    const isHover = node === hoverCell;
    const isSelected = graph.current.isSelected(node);
    let htmlDiv = null;
    const view = graph.current?.findViewByCell(node);

    if (view && view.container) {
      htmlDiv = view.container.querySelector('div');
    }

    if (htmlDiv) {
      htmlDiv.style.overflow = 'hidden';
      htmlDiv.style.borderRadius = '12px';
      htmlDiv.style.border = isHover || isSelected
        ? '1px solid #B620E0'
        : `1px solid ${mode === 'dark' ? '#6f7f95' : '#e9e2f4'}`;
    }
  }
  const [nodeData, setNodeData] = useState([]);
  const getNodeData = () => {
    if (graph.current) {
      const nodes = graph.current.getNodes();
      const nodeDataList = nodes.map((node: any) => {
        return node.getData();
      });
      console.log('nodeDataList', nodeDataList)
      setNodeData(nodeDataList);
    }
  }

  const checkNodeConnections = () => {
    const nodes = graph.current.getNodes();
    let hasIsolatedNode = false;
    if (nodes?.length == 1) return true;
    nodes.forEach((node) => {
      const incomingEdges = graph.current.getIncomingEdges(node);
      const outgoingEdges = graph.current.getOutgoingEdges(node);
      // console.log('incomingEdges,', incomingEdges, outgoingEdges)
      if (!incomingEdges?.length && !outgoingEdges?.length) {
        console.log(`节点 ${node.id} 没有任何连线`);
        hasIsolatedNode = true;

        let htmlDiv = null
        const view = graph.current?.findViewByCell(node);
        if (view && view.container) {
          htmlDiv = view.container.querySelector('div');
        }

        if (htmlDiv) {
          htmlDiv.style.borderRadius = '4px';
          htmlDiv.style.border = '1px solid red';
        }
      }
    });

    if (hasIsolatedNode) {
      console.error('存在没有连线的节点，请确保所有节点至少有一个连线。');
      return false;
    }

    return true;
  }
  const [checkedState, setCheckedState] = useState({} as { [key: string]: boolean });
  const handleCheckboxChange = (key: string, isChecked: boolean) => {
    setCheckedState((prevState) => ({
      ...prevState,
      [key]: isChecked
    }));
  };

  const applyDagreLayout = () => {
    if (!graph.current) return;

    // const dagreLayout = new DagreLayout({
    //   type: 'dagre',
    //   rankdir: 'TB', // 从上到下布局 (可选值: 'TB', 'BT', 'LR', 'RL')
    //   align: 'UL', // 对齐方式 (可选值: 'UL', 'UR', 'DL', 'DR')
    //   nodesep: 66, // 节点之间的水平间距
    //   ranksep: 66, // 节点之间的垂直间距
    // });

    // const nodes = graph.current.getNodes().map((node: any) => ({
    //   id: node.id,
    //   data: node.getData(),
    //   width: node.size().width,
    //   height: node.size().height,
    // }));

    // const edges = graph.current.getEdges().map((edge: any) => ({
    //   source: edge.getSourceCellId(),
    //   target: edge.getTargetCellId(),
    // }));

    // const layoutData = dagreLayout.layout({ nodes, edges });
    // if (layoutData.nodes?.length) {
    //   layoutData.nodes.forEach((node: any) => {
    //     const graphNode = graph.current.getCellById(node.id);
    //     if (graphNode) {
    //       graphNode.position(node.x, node.y);
    //     }
    //   });
    // }
    const nodes = graph.current.getNodes();
    if (!nodes.length) return;

    const maxPerRow = 3; // 每行最多 3 个节点
    const nodeWidth = NODE_WIDTH; // 节点宽度
    const nodeHeight = NODE_HEIGHT; // 节点高度
    const horizontalSpacing = -120; // 节点之间的水平间距
    const verticalSpacing = 66; // 节点之间的垂直间距

    nodes.forEach((node: any, index: number) => {
      const row = Math.floor(index / maxPerRow);
      const col = index % maxPerRow;

      const x = col * (nodeWidth + horizontalSpacing);
      const y = row * (nodeHeight + verticalSpacing);

      node.position(x, y);
    });

    graph.current.centerContent();
    canvasResizeChange();
  };

  useEffect(() => {
    applyDagreLayout();
    setNodeData([]);
    const checkedStateObj: any = {};
    graph?.current?.clearCells?.();
    nodeCount.current = 1;
    if (!currentItem?.modelInfo) {
      setCheckedState(checkedStateObj);
      return;
    }
    const {
      statisticalGranularity, polymerizationMode,
      datasourceId,
    } = currentItem.modelInfo || {};
    // 统计粒度
    if (statisticalGranularity) {
      for (const i of statisticalGranularity.split(',').filter(Boolean)) {
        checkedStateObj[`tjld-${i}`] = true;
      }
    }
    // 聚合方式
    if (polymerizationMode) {
      for (const i of polymerizationMode.split(',').filter(Boolean)) {
        checkedStateObj[`jhfs-${i}`] = true;
      }
    }

    setCheckedState(checkedStateObj);
    console.log('currentI3232324332tem', checkedStateObj, nodeData, currentItem)

    // 画布回显
    showCanvasChange();
    canvasResizeChange();
  }, [currentItem])

  function groupJoinData(items) {
    const grouped: any = {};

    items.forEach((item: any) => {
      const sourceKey = item.sourceTableName || item.sourceTableId;
      const targetKey = item.targetTableName || item.targetTableId;
      const compositeKey = `${sourceKey}-${targetKey}`;

      if (!grouped[compositeKey]) {
        grouped[compositeKey] = {
          ...item,
          metricModelId: item.metricModelId,
          sourceData: sourceKey,
          join: item.joinType,
          targetData: targetKey,
          fields: []
        };
      }

      grouped[compositeKey].fields.push({
        lField: item.sourceColumn,
        rField: item.targetColumn
      });
    });
    const edgeInfo: any = Object.values(grouped);
    if (edgeInfo?.length) {
      for (const i of edgeInfo) {
        const { sourceTableName, targetTableName, sourceTableId, targetTableId, joinType, fields, } = i || {};

        const sourceKey = sourceTableName || sourceTableId;
        const targetKey = targetTableName || targetTableId;
        if (!sourceKey || !targetKey) return;

        let data: any = {
          sourceData: sourceKey,
          join: joinType,
          targetData: targetKey,
          fields
        }
        graph.current.addEdge({
          ...EDGE,
          source: { cell: sourceKey, port: 'port2' },
          target: { cell: targetKey, port: 'port1' },
          labels: [
            {
              attrs: {
                label: {
                  text: joinType,
                },
              },
              tools: [
                {
                  name: 'button-remove',
                  args: { distance: -40 },
                },
              ],
            }
          ],
          data: {
            ...data
          }
        })
      }
    }
    // console.log('Object.values(grouped),', grouped, Object.values(grouped),)
  }

  const showCanvasChange = () => {
    if (!graph.current) return;
    if (!currentItem?.modelInfo) {
      return;
    }

    const {
      metricModelTables, metricModelTableRelationships
    } = currentItem.modelInfo || {};
    // 节点
    if (metricModelTables?.length) {
      for (const i of metricModelTables) {
        handleAddNode({
          id: i.id || i.name,
          dataList: [...i.metricModelTableColumns || []].map((item: any) => {
            const obj = {
              ...item,
              field: item.name,
              name: item.comment,
              metrics: item.metricType,
              // isTimeDimension: !!item.isTimeDimension,
              // columnPrecision: item.columnPrecision,
            };
            if (obj.metrics == DimensionMeasurementEnum.Measurement) {
              obj.dataType = dataTypeEnum.NUMBER;
              obj.columnPrecision = item.columnPrecision;
            } else if (obj.metrics == DimensionMeasurementEnum.Dimension && !obj.isTimeDimension) {
              obj.dataType = dataTypeEnum.STRING;
              obj.enableCodeTable = item.enableCodeTable;
              obj.codeTableName = item.codeTableName;
            } else if (obj.metrics == DimensionMeasurementEnum.Dimension && obj.isTimeDimension) {
              obj.dataType = dataTypeEnum.TIME;
            }
            return obj;
          }),
          tableType: i.tableType ? '1' : '0',
          describe: i.tableType ? i.querySqlId : i.name,
          x: i.x,
          y: i.y,
        })
        // console.log('节点', i)
      }
    }

    // 节点连线
    if (metricModelTableRelationships?.length) {
      groupJoinData(metricModelTableRelationships)

    }

    getNodeData();
    // const data2 = graph.current.toJSON();
    // console.log('保存的数据:', currentItem, graph.current, '---', data2, '---', _.cloneDeep(data2));
  }
  const updateStatusChange = async (getCurrentItemChange: () => void) => {
    console.log('currentItem?.modelInfo?.id', currentItem?.modelInfo?.id)
    if (!currentItem?.modelInfo?.id) return;
    const params = {
      status: !currentItem.modelInfo?.status,
      id: currentItem.modelInfo.id,
    }
    const res = await updateStatus(params);
    const MSG = !currentItem.modelInfo?.status ? '发布' : '下线';
    if (res.data.code == 0) {
      getCurrentItemChange();
      message.success(res.data.msg || `${MSG}成功!`);
    } else {
      message.error(res.data.msg || `${MSG}失败!`);
    }
  }
  const [edgeContextMenu, setEdgeContextMenu] = useState<{ edge: any, x: number, y: number, cell: any } | null>(null);
  const closeEdgeContextMenu = useCallback(() => setEdgeContextMenu(null), []);
  return {
    container,
    removeNode,
    updateNodeData,
    updateNodeStyle,
    handleAddNode,
    handleSave,
    nodeData,
    checkNodeConnections,
    checkedState,
    handleCheckboxChange,
    toJSONChange,
    updateStatusChange,
    edgeContextMenu,
    closeEdgeContextMenu,
    handleCreate,
    graph,
  };
}